// 商品分类
import api from '@/tools/api.js'
import promise from '@/tools/promise'
import { SUCCESS_STATUS } from '@/config/status'
import {
  GOODS_CLASS_TREE,
  GOODS_CLASS_INFO,
  GOODS_CLASS_COVER,
  GOODS_CLASS_SAVE_DATA
} from '@/store/mutation-types'

const state = {
  goodsTree: [],
  goodsClassInfo: {},
  cover: {},
  saveData: {},
  attrsInfo: [],
  attrsList: []
}

// mutations
const mutations = {
  [GOODS_CLASS_TREE] (state, payload) {
    state.goodsTree = payload
  },
  [GOODS_CLASS_INFO] (state, payload) {
    state.goodsClassInfo = payload
    state.attrsList = payload.allAttrInfo
    let attrsInfo = []
    for (let i = 0; i < Number(payload.allAttrInfo.length); i++) {
      attrsInfo[i] = {en_name: payload.allAttrInfo[i].en_name, value: ''}
    }
    state.attrsInfo = attrsInfo
  },
  [GOODS_CLASS_COVER] (state, data) {
    state.cover = data
  },
  [GOODS_CLASS_SAVE_DATA] (state, data) {
    state.saveData = data
  }
}

// actions
const actions = {
  // 获取商品分类树
  async goodsClassTree ({ commit }, payload) {
    let treeRes = await api('servergoods/goods/GoodsCategory/goodsCateList', payload)
    if (SUCCESS_STATUS === treeRes.status) {
      commit(GOODS_CLASS_TREE, treeRes.res)
    }
  },
  // 改变商品分类状态
  async changeStatus ({ commit }, payload) {
    let statusRes = await api('servergoods/goods/GoodsCategory/changeCateStatus', payload)
    return promise(statusRes)
  },
  // 删除商品分类
  async goodsClassDel ({ commit }, payload) {
    let delRes = await api('servergoods/goods/GoodsCategory/delCate', payload)
    return promise(delRes)
  },
  // 获取商品分类详情
  async goodsClassInfo ({ commit }, payload) {
    let infoRes = await api('servergoods/goods/GoodsCategory/oneCateInfo', payload)
    if (SUCCESS_STATUS === infoRes.status) {
      commit(GOODS_CLASS_INFO, infoRes.res)
    }
  },
  // 编辑商品分类
  async goodsClassEdit ({ commit }, payload) {
    let editRes = await api('servergoods/goods/GoodsCategory/editGoodsCate', payload)
    return promise(editRes)
  },
  // 添加商品分类
  async goodsClassAdd ({ commit }, payload) {
    let addRes = await api('servergoods/goods/GoodsCategory/addGoodsCate', payload)
    return promise(addRes)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
